const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const cors = require('cors')
const gatewayPlugin = require('./plugins/gatewayPlugin')
const framework = require('../framework')

// 读取服务配置
const appConfig = framework.common.assertAndGetAppConfig('application.json')

//获取路由
function getRouter(remoteConfig) {
  let mapper = {}
  mapper[remoteConfig.serviceName] = {
    GET: true,
    POST: true,
    suffix: '/:service/:role/:cmd'
  }
  return [
    {
      pin: 'service:*',
      prefix: '/api',
      map: mapper
    }
  ]
}

// 初始化express
function initExpress(scenca, remoteConfig) {
  const server = scenca.export('web/context')()
  server
    .use(
      cors({
        origin: remoteConfig.cors.origin,
        methods: remoteConfig.cors.methods,
        alloweHeaders: remoteConfig.cors.alloweHeaders
      })
    )
    .use(bodyParser.json())
    .use(cookieParser())
    .get('*', (req, res) => res.status(404).send('Not found'))
    .listen(remoteConfig.port, () => {
      framework.logger.info(
        `${remoteConfig.alias} is running on port ${remoteConfig.port}`
      )
    })
}

// 初始化Seneca
framework.generator1.createWebServer(
  appConfig.pin,
  gatewayPlugin,
  appConfig.redis,
  getRouter,
  initExpress
)
